package io.web.usercenter.controller;

import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.config.ConfigureBuilder;
import com.deepoove.poi.policy.AbstractRenderPolicy;
import com.deepoove.poi.render.RenderContext;
import io.swagger.annotations.ApiOperation;
import io.web.usercenter.vo.FindObj;
import io.web.usercenter.vo.FindParam;
import org.apache.poi.xwpf.usermodel.BreakType;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * WordController.
 *
 * @date 2024-08-09
 */
@Controller
public class WordController {

    /**
     * 导出文件不加这个可能会乱码
     * @ApiOperation(value = "导出", produces = "application/octet-stream")
     *
     * @param response
     * @throws Exception
     */
    @ApiOperation(value = "导出", produces = "application/octet-stream")
    @GetMapping("/downloadWord")
    public void downloadWord(HttpServletResponse response) throws Exception {
        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition","attachment;filename=\""+"out_template.docx"+"\"");

// HttpServletResponse response
        OutputStream out = response.getOutputStream();
        BufferedOutputStream bos = new BufferedOutputStream(out);

        ConfigureBuilder builder = Configure.builder();
        // 开启spring表达式
        builder.useSpringEL();
        builder.bind("produces.newPage", new AbstractRenderPolicy<Object>() {
            @Override
            public void doRender(RenderContext<Object> renderContext) throws Exception {
                XWPFRun where = renderContext.getWhere();
                where.setText("dddd", 0);
                where.addBreak(BreakType.PAGE);
            }
        });

        FindParam findParam = new FindParam();

        FindObj f1 = new FindObj();
        f1.setFindingTitle("关联方信息更新不及时");
        f1.setNewPage("f1");
        FindObj f2 = new FindObj();
        f2.setFindingTitle("关联方信息更新不及时f2");
        f2.setNewPage("f2");

        findParam.getProduces().add(f1);
        findParam.getProduces().add(f2);


        XWPFTemplate template = XWPFTemplate.compile("C:\\Users\\wangwenjie\\Desktop\\tl-template.docx", builder.build()).render(findParam);

        template.write(bos);

        bos.flush();
        out.flush();
    }
}
